<template>
  <div>
    <!-- {{ sysUserForm }} -->
    <el-form ref="sysUserForm" :disabled="formDis" :model="sysUserForm" :rules="rules" label-width="100px" class="demo-ruleForm" style="margin-top: 20px;">
      <el-form-item label="用户名" prop="username">
        <el-col :span="6" >
          <el-input :disabled="isEdit" v-model="sysUserForm.username" maxlength="20" />
        </el-col>
      </el-form-item>
      <!-- <el-form-item v-if="isEdit" label="密码" prop="newPassword">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.newPassword" type="password" />
        </el-col>
      </el-form-item> -->
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.password" type="password" />
        </el-col>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword" >
        <el-col :span="6" >
          <el-input v-model="sysUserForm.confirmPassword" type="password" />
        </el-col>
      </el-form-item>
      <el-form-item v-if="isEdit" label="密码" prop="changePassword">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.changePassword" type="password" @blur="passBlur('sysUserForm')" />
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="头像">
        <el-upload
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :before-upload="beforeAvatarUpload"
          :on-success="change"
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :data="uploadData"
          :action="actionUrl"
          with-credentials
          multiple
          class="upload-demo"
          accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</div>
        </el-upload>
        <img :src="sysUserForm.headImg" :v-if="sysUserForm.headImg" :style="sysUserForm.headImg ? 'width: 126px;' : ''" alt="">
      </el-form-item> -->
      <el-form-item label="姓名" prop="name">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.name" />
        </el-col>
      </el-form-item>
      <el-form-item v-if="selectShow" label="角色" prop="roleId">
        <el-col :span="6" >
          <el-select v-model="sysUserForm.roleId" placeholder="请选择角色" @change="changeRoleId">
            <el-option v-for="(item, index) in role" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="手机号" prop="phone">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.phone" />
        </el-col>
      </el-form-item> -->
      <el-form-item label="电话" prop="phone">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.phone" />
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="传真" prop="fax">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.fax" />
        </el-col>
      </el-form-item> -->
      <el-form-item label="EMAIL" prop="email">
        <el-col :span="6" >
          <el-input v-model="sysUserForm.email" />
        </el-col>
      </el-form-item>
      <el-form-item v-if="selectShow" label="状态" prop="availableStatus">
        <el-select v-model="sysUserForm.availableStatus" placeholder="请选择状态">
          <el-option :value="1" :label="'启用'" />
          <el-option :value="0" :label="'禁用'" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-if="isEdit" type="primary" @click="submitForm('sysUserForm')">确定</el-button>
        <el-button v-else type="primary" @click="submitForm('sysUserForm')">确定</el-button>
        <el-button v-preventReClick v-if="!formDis" :disabled="false" @click="$router.go(-1)">关闭</el-button>
        <!-- <el-button @click="resetForm('sysUserForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import config from '@/utils/config';
import { checkPhone, checkIdCard } from '@/utils/regUtil';
import { checkNotEmail, checkNum } from '@/utils/validateUtil';
import { getRoleList } from '@/api/sysRole'
import { addServerUser, editServerUser } from '@/api/sysUser'
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'

const url = ''

const validateName = (rule, value, callback) => {
  const reg = /^[\u4e00-\u9fa5 ]{2,10}$/;
  const reg1 = /^[a-zA-Z\/ ]{4,40}$/;
  if (!reg.test(value) && !reg1.test(value)) {
    callback(new Error())
  }
  callback()
};
const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入正确的密码格式，数字+字母'));
  } else if (value.toString().length < 6 || value.toString().length > 20) {
    callback(new Error('密码长度为6 - 20个字符'))
  } else {
    callback();
  }
};
const validateEditPass = (rule, value, callback) => {
  if (!value) {
    callback();
    // callback(new Error('请输入正确的密码格式，数字+字母'));
  } else if (value.toString().length < 6 || value.toString().length > 20) {
    callback(new Error('密码长度为6 - 20个字符'))
  } else {
    callback();
  }
};
const validateNewPass = (rule, value, callback) => {
  if (value.toString().length < 6 || value.toString().length > 20) {
    callback(new Error('密码长度为6 - 20个字符'))
  } else {
    callback();
  }
};
const validatephone = (rule, value, callback) => {
  if (!checkPhone(value)) {
    callback(new Error())
  }
  callback();
};
const validateMail = (rule, value, callback) => {
  if (!checkNotEmail(value)) {
    callback(new Error())
  }
  callback();
};
const validateNum = (rule, value, callback) => {
  if (!checkNum(value)) {
    callback(new Error())
  }
  callback();
};

export default {
  name: 'TinymceDemo',
  components: { Tinymce },
  data() {
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.sysUserForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      role: [],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 20, message: '最多20个字符', trigger: 'blur' },
          { pattern: /^[0-9a-zA-Z_]{1,}$/, message: '请输入字母，数字', trigger: 'blur' }
        ],
        newWatchPassword: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
          // { validator: validatePass, trigger: 'blur' }
        ],
        newPassword: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' }
        ],
        password: [
          { required: !this.isEdit, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' },
          { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/, message: '请输入字母+数字', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请输入6-20位密码可选英文数字以及字符', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        changePassword: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '请输入6-20位密码', trigger: 'blur' },
          { validator: validateEditPass, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { validator: validateName, message: '姓名格式为2-10个中文或4-20个英文', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatephone, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        availableStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // 非必填累类
        email: [
          { required: false, message: '请输入邮箱地址', trigger: 'blur' },
          { max: 100, message: '长度在 100 个字符之内', trigger: 'blur' },
          { validator: validateMail, message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        // phone: [
        //   { required: true, message: '请输入电话', trigger: 'blur' },
        //   { validator: validateNum, message: '请输入正确的电话号码', trigger: 'blur' }
        // ],
        fax: [
          { required: false, message: '请输入传真', trigger: 'blur' },
          { validator: validateNum, message: '请输入正确的传真号码', trigger: 'blur' }
        ]
      },
      sysUserForm: {
        username: '',
        password: '',
        confirmPassword: '',
        changePassword: '',
        // newPassword: '',
        roleIds: [],
        roleId: '',
        name: '',
        phone: '',
        availableStatus: '',
        // headImg: '',
        // fax: '',
        email: ''
      },
      password: '',
      confirmPassword: '',
      fileList: [],
      actionUrl: config.BaseUrl + '/image/upload',
      uploadData: {
        key: '',
        token: ''
      },
      formDis: false,
      isEdit: false,
      selectShow: false,
      changePassword: ''
    }
  },
  created() {
    getRoleList().then(response => {
      this.role = response.data.list
      console.log(this.role)
      // this.oldPassword = response.data.list.password
      // console.log('this.oldPassword', this.oldPassword)
    })
  },
  mounted() {
    console.log('this.$route.query:', this.$route.query)
    const _self = this;
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? Boolean(_self.$route.query.isEdit) : false;
      this.formDis = Boolean(this.$route.query.isLook)
      const a = this.$route.query
      console.log('新增编辑角色：：：', a)
      if (a.hasOwnProperty('isLook')) {
        delete a.isLook;
      }
      if (a.hasOwnProperty('isEdit')) {
        delete a.password;
        delete a.isEdit;
      }
      console.log(typeof this.sysUserForm.availableStatus)
      // this.sysUserForm.availableStatus = Number(this.sysUserForm.availableStatus)
      this.sysUserForm = a
    } else {
      this.resetForm('sysUserForm')
    }
    this.selectShow = true
  },
  methods: {
    passBlur(name) {
      console.log(name)
      setTimeout(() => {
        this.$refs[name].clearValidate();
      }, 3000)
    },
    changeRoleId() {
      this.sysUserForm.roleIds = [this.sysUserForm.roleId]
      // this.$set(this.sysUserForm.roleIds, 0, this.sysUserForm.roleId)
    },
    submitForm(formName) {
      // console.log('--->')
      // console.log(this.$refs[formName])
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // this.$set(this.sysUserForm.roleIds, 0, this.sysUserForm.roleId)
          this.sysUserForm.roleIds = [this.sysUserForm.roleId]
          this.request(this.sysUserForm)
        } else {
          return false;
        }
      });
    },
    request(data) {
      if (this.isEdit) {
        if (data.changePassword !== '') {
          data.password = data.changePassword
        } else {
          delete data.password
        }
        delete data.changePassword
        console.log('编辑：', data)
        editServerUser(data).then(response => {
          if (Number(response.code) === 200) {
            Message.success('编辑成功')
            this.$router.go(-1);
          } else {
            Message.error(response.message + '-' + response.data)
          }
        })
      } else {
        // 新增
        console.log(data)
        addServerUser(data).then(response => {
          if (Number(response.code) === 200) {
            Message.success('新增成功')
            this.$router.go(-1);
          } else {
            if (response.code === '4003') {
              Message.error(response.message + '-' + '用户名或者手机号重复')
            } else {
              Message.error(response.message + '-' + response.data)
            }
          }
        });
      }
    },
    resetForm(formName) {
      // this.$store.dispatch('resetFunc').then(() => {
      // }).catch((err) => {
      //   Message.error(err.err)
      // })
    }
    // handleRemove(file, fileList) {},
    // handlePreview(file) {},
    // handleExceed(files, fileList) {
    //   this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    // },
    // beforeRemove(file, fileList) {
    //   if (file && file.availableStatus === 'success') {
    //     return this.$confirm(`确定移除 ${file.name}？`).then(() => {
    //       url = ''
    //     })
    //   }
    // },
    // beforeAvatarUpload(file) {
    //   // var observable = qiniu.upload(file, key, token, putExtra, config)
    //   console.log(file.type)
    //   const isPNG = file.type === 'image/png'
    //   const isJPEG = file.type === 'image/jpeg'
    //   const isJPG = file.type === 'image/jpg'
    //   const isGIF = file.type === 'image/gif'
    //   const isLt2M = file.size / 1024 / 1024 < 2
    //   if (!isPNG && !isJPEG && !isJPG && !isGIF) {
    //     this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!')
    //   } else {
    //     this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
    //   }
    //   console.log(isPNG, isJPEG, isLt2M)
    //   console.log(isLt2M && isPNG || isJPEG || isJPG)
    //   return isLt2M && isPNG || isJPEG || isJPG || isGIF
    // },
    // change(file, fileList) {
    //   if (Number(fileList.response.code) === 200) {
    //     const objectNew = {
    //       headImg: config.ImgUrl + fileList.response.data
    //     }
    //     this.sysUserForm.headImg = config.ImgUrl + fileList.response.data

    //     // this.$store.dispatch('addListenerHeadImg', objectNew).then(() => {
    //     //   Message.success('图片上传成功')
    //     // }).catch((err) => {
    //     //   Message.error(err.err)
    //     // })
    //   } else {
    //     Message.error('图片上传失败')
    //   }
    // }
  }
}
</script>

<style>
</style>
